var inspec = {},customerId='',$quantityTotal=$('#quantityTotal'),$totalPriceTotal=$('#totalPrice'),$cartonTotal=$('#cartonTotal'),$netWeightTotal=$('#netWeightTotal'),$grossWeightTotal=$('#grossWeightTotal');
layui.use(['layer','form','laytpl'], function() {
    var layer = layui.layer, form = layui.form,laytpl=layui.laytpl;
    var id = getUrlParam('id'),keys = ['model','name','brand','unitName','quantity','unitPrice','totalPrice','cartonNum','cartonNo','netWeight','grossWeight','countryName','goodsCode'];
    var splitQtywin;
    inspec = {
        renderData:function (){
            show_loading();
            $.post(rurl('scm/impOrder/detail'),{'id':id,'operation':'order_inspection'},function (res) {
                if(isSuccessWarnClose(res)){
                    var data=res.data,order=data.order,logistiscs=data.logistiscs,members=data.members||[];
                    customerId = order.customerId;
                    laytpl($('#orderViewTemp').html()).render(order,function (html) {
                        $('#orderView').html(html);
                    });
                    laytpl($('#logistiscsViewTemp').html()).render(logistiscs,function (html) {
                        $('#logistiscsView').html(html);
                    });
                    inspec.createRows(members);

                    $('.confirm-inspection').removeClass('layui-btn-disabled').attr({'disabled':null});
                    $('.edit-member').show();
                    $('.save-edit-member').hide();
                }
            });
        },
        createRows:function (members) {
            var mhtml = [],tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
            $.each(members,function (i,o) {
                mhtml.push(inspec.createRowHtml(o));
                tquantity+=o.quantity;ttotalPrice+=o.totalPrice;tcartonNum+=o.cartonNum;tnetWeight+=o.netWeight;tgrossWeight+=o.grossWeight;
            });
            $('#materialBody').html(mhtml.join(''));
            inspec.historyMembers();
            $quantityTotal.html(Math.round(tquantity*100)/100);
            $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
            $cartonTotal.html(tcartonNum);
            $netWeightTotal.html(Math.round(tnetWeight*100)/100);
            $grossWeightTotal.html(Math.round(tgrossWeight*100)/100);
            autoAllModel();
            autoUnit();
            autoCountry();
            initInput();

        },
        createRowHtml:function(o){
            return [
                '<tr mid="'+o.id+'"><td class="t-a-c">'+o.rowNo+'</td>',
                '<td class="t-a-c"><input type="hidden" name="id" LIST value="'+o.id+'"/><span class="'+o.materielStatusId+'">'+o.materielStatusName+'</span></td>',
                '<td><div class="m-text" model>'+o.model+'</div><div class="m-input"><input type="text" name="model" LIST class="layui-input required auto-customer-model" placeholder="型号" value="'+(isEmpty(o.model)?'':o.model)+'"/></div></td>',
                '<td><div class="m-text" name>'+o.name+'</div><div class="m-input"><input type="text" name="name" LIST class="layui-input" value="'+(isEmpty(o.name)?'':o.name)+'"/></div></td>',
                '<td><div class="m-text" brand>'+o.brand+'</div><div class="m-input"><input type="text" name="brand" LIST class="layui-input required" value="'+(isEmpty(o.brand)?'':o.brand)+'"/></div></td>',
                '<td><div class="m-text" unitName>'+o.unitName+'</div><div class="m-input"><input type="text" name="unitName" LIST class="layui-input auto-unit required" value="'+(isEmpty(o.unitName)?'个':o.unitName)+'"/></div></td>',
                '<td><div class="m-text" quantity>'+formatCurrency(o.quantity)+'</div><div class="m-input"><input type="text" name="quantity" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(o.quantity)?'':o.quantity)+'"/></div></td>',
                '<td class="t-a-c"><div class="m-text"><a href="javascript:" class="blue-a" onclick="inspec.splitQuantity(\''+o.id+'\')"><i class="fa fa-minus-circle"></i></a></div></td>',
                '<td><div class="m-text" unitPrice>'+o.unitPrice+'</div><div class="m-input"><input type="text" name="unitPrice" LIST class="layui-input layui-disabled" readonly value="'+(isEmpty(o.unitPrice)?'0.0000':o.unitPrice)+'"/></div></td>',
                '<td><div class="m-text" totalPrice>'+formatCurrency(o.totalPrice)+'</div><div class="m-input"><input type="text" name="totalPrice" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(o.totalPrice)?'':o.totalPrice)+'"/></div></td>',
                '<td><div class="m-text" cartonNum>'+o.cartonNum+'</div><div class="m-input"><input type="text" name="cartonNum" LIST onblur="calculationAll()" INT class="layui-input" value="'+(isEmpty(o.cartonNum)?'0':o.cartonNum)+'"/></div></td>',
                '<td><div class="m-text" cartonNo>'+removeNull(o.cartonNo)+'</div><div class="m-input"><input type="text" name="cartonNo" LIST class="layui-input required" value="'+(isEmpty(o.cartonNo)?'':o.cartonNo)+'"/></div></td>',
                '<td><div class="m-text" netWeight>'+o.netWeight+'</div><div class="m-input"><input type="text" name="netWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(o.netWeight)?'0.0000':o.netWeight)+'"/></div></td>',
                '<td><div class="m-text" grossWeight>'+o.grossWeight+'</div><div class="m-input"><input type="text" name="grossWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(o.grossWeight)?'0.0000':o.grossWeight)+'"/></div></td>',
                '<td><div class="m-text" countryName>'+o.countryName+'</div><div class="m-input"><input type="text" name="countryName" LIST class="layui-input auto-country required" value="'+(isEmpty(o.countryName)?'中国':o.countryName)+'"/></div></td>',
                '<td><div class="m-text" goodsCode>'+o.goodsCode+'</div><div class="m-input"><input type="text" name="goodsCode" LIST class="layui-input" value="'+(isEmpty(o.goodsCode)?'':o.goodsCode)+'"/></td>',
                '<td class="pl5"><a href="javascript:" onclick="inspec.bindReceivingNoteNo(\''+o.id+'\','+o.quantity+')" class="blue-a" title="绑定入库单"><i class="fa fa-plus-circle"></i>'+removeNull(o.receivingNoteNo)+'</a></td>',
                '<td class="t-a-c"><div class="m-input"><a href="javascript:" class="blue-a" onclick="inspec.removeMember(this)">删除</a></div></td>',
                '</tr>'
            ].join('');
        },
        historyMembers:function () {
            $.post(rurl('scm/impOrderMemberHistory/list'),{'orderId':id},function (res) {
                if(isSuccess(res)){
                    $.each(res.data || [],function (i,o) {
                        var midObj = $('tr[mid="'+o.id+'"]');
                        if(midObj.size()>0){
                            $.each(keys,function (j,k) {
                                var keyObj = midObj.find('['+k+']');
                                if(keyObj.size()==1){
                                    var oval = removeNull(o[k]+''),nval = keyObj.html();
                                    if('quantity'==k||'totalPrice'==k){
                                        oval = formatCurrency(o[k]);
                                    }
                                    if(oval!=nval){
                                        keyObj.html('<div class="original-info">'+oval+'</div><div class="new-info">'+nval+'</div>');
                                    }
                                }
                            });
                        }
                    });
                }
            });
        },
        bindReceivingNoteNo:function (mid,qty) {
            show_loading();
            $.post(rurl('scm/orderMemberReceivingNo/item'),{'orderMemberId':mid},function (res) {
                if(isSuccess(res)){
                    if(res.data.length==0){
                        res.data = [{'receivingNo':'','quantity':qty}];
                    }
                    laytpl($('#bindReceivingNoteViewTemp').html()).render(res.data,function (html) {
                        var rnwin = layer.open({
                            type: 1,shadeClose:true,title:'绑定入库单',area: ['420px', '240px'],content: html,
                            success:function () {
                                $('.close-mrn').unbind().click(function (){layer.close(rnwin);});
                                initInput();
                                autoReceivingNo($('input[name="receivingNo"]'));
                                $('.addrow-btn').click(function () {
                                    var $tbody = $(this).parent().parent().parent().parent().find('tbody'),reuuid = uuid();
                                    $tbody.append([
                                        '<tr class="edit"><td><input type="text" name="receivingNo" id="'+reuuid+'" LIST class="layui-input required" placeholder="入库单号"/></td>',
                                        '<td><input type="text" name="quantity" LIST  NUMBER class="layui-input required" placeholder="绑定数量"/></td>',
                                        '<td class="t-a-c"><a href="javascript:" onclick="deleteRow(this)"><i class="fa fa-trash-o"></i></a></td></tr>'
                                    ].join(''));
                                    initInput();
                                    autoReceivingNo($('#'+reuuid));
                                });
                                $('.save-bind-receiving').click(function () {
                                    var $rform = $('.receiving-form');
                                    if(!checkedForm($rform)){return;}
                                    var receivingNos = jsonList($rform.serializeJson());
                                    postJSON('scm/impOrder/saveBindMember',{"memberId":mid,"receivingNos":receivingNos},function (res) {
                                        show_success('绑定成功');
                                        layer.close(rnwin);
                                        inspec.renderData();
                                    });
                                });
                            }
                        });
                    });
                }
            });
        },
        saveSplitMember:function (members) {
            postJSON('scm/impOrder/saveSplitMember',{'orderId':id,'members':members},function (res) {
                show_success('拆分成功');
                layer.close(splitQtywin);
                inspec.renderData();
            });
        },
        splitQuantity:function (mid) {
            show_loading();
            $.get(rurl('scm/impOrder/obtainSplitMember'),{'id':mid},function (res) {
                if(isSuccess(res)){
                    var data = res.data,members = [];
                    members.push(data);
                    members.push({
                        id:'',
                        model:data.model,
                        name:data.name,
                        brand:data.brand,
                        unitName:data.unitName,
                        quantity:0,
                        unitPrice:0,
                        totalPrice:0,
                        cartonNum:0,
                        netWeight:0,
                        grossWeight:0,
                        cartonNo:data.cartonNo,
                        countryName:data.countryName
                    });
                    laytpl($('#splitQtyViewTemp').html()).render(members,function (html) {
                        splitQtywin = layer.open({
                            type: 1,shadeClose:true,title:'拆分产品',area: ['1100px', '340px'],content: html,
                            success:function () {
                                $('.close-mrn').unbind().click(function (){layer.close(splitQtywin);});
                                initInput();
                                autoCountry();

                                $('.save-split-quantity').click(function () {
                                    var $rform = $('.split-qty-form');
                                    if(!checkedForm($rform)){return;}
                                    var members = jsonList($rform.serializeJson());
                                    var tq = Math.round(parseFloat($('#s_quantity').html())*100)/100,tt = Math.round(parseFloat($('#s_totalPrice').html())*100)/100;
                                    if(data.quantity!=tq || data.totalPrice != tt){
                                        confirm_inquiry('拆分后明细总数量或总价与原始明细不一致是否保存？',function () {
                                            inspec.saveSplitMember(members);
                                        });
                                    }else{
                                        inspec.saveSplitMember(members);
                                    }
                                });
                            }
                        });
                    });
                }
            });
        },
        removeMember:function (e) {
            confirm_inquiry('您是否确定要删除此订单明细？',function () {
                var $per = $(e).parent().parent().parent();
                $per.remove();
                calculationAll();
            });
        }
    };
    inspec.renderData();
    $('.file-size').attr({'doc-id':id});
    initFileSize();

    $('.share-net-weight').click(function () {
        layer.prompt({id:'snwei',formType:3,maxlength: 12,title:'请填写总净重',success:function () {$('#snwei').find('input').attr({'NUMBER':''});initInput();}},function(val, index){
            show_loading();
            $.post(rurl('scm/impOrder/shareNetWeight'),{'id':id,'netWeight':val},function (res) {
                if(isSuccess(res)){
                    layer.close(index);
                    inspec.renderData();
                    show_success('分摊成功');
                }
            });
        });
    });

    $('.share-gross-weight').click(function () {
        layer.prompt({id:'sgwei',formType:3,maxlength: 12,title:'请填写总毛重',success:function () {$('#sgwei').find('input').attr({'NUMBER':''});initInput();}},function(val, index){
            show_loading();
            $.post(rurl('scm/impOrder/shareGrossWeight'),{'id':id,'grossWeight':val},function (res) {
                if(isSuccess(res)){
                    layer.close(index);
                    inspec.renderData();
                    show_success('分摊成功');
                }
            });
        });
    });
    $('.edit-member').click(function () {
        $('#materialBody').find('tr').addClass('edit');
        $('.confirm-inspection').addClass('layui-btn-disabled').attr({'disabled':true});
        $(this).hide();
        $('.save-edit-member').show();
    });
    $('.print-checklist').click(function () {
        openwin('order/imp/print-checklist.html?id='+id,'核对单打印',{ area: ['1000px', '0px'],shadeClose:true});
    });
    $('.batch-receiving-no').click(function () {
        layer.prompt({id:'bindReceivingNo',formType:3,maxlength: 20,title:'请填写入库单号(可模糊搜索)，本操作为批量绑定入库单号',success:function () {
                autoReceivingNo($('#bindReceivingNo').find('input'));
            }},function(val, index){
                show_loading();
                $.post(rurl('scm/impOrder/batchReceivingNo'),{'id':id,'receivingNo':val},function (res) {
                    if(isSuccess(res)){
                        layer.close(index);
                        inspec.renderData();
                        show_success('操作成功');
                    }
                });
        });
    });
    var taskArg = {'operation':'order_inspection','documentId':id,'documentClass':'ImpOrder','newStatusCode':'waitEdit'};
    //退回修改
    $('.back-business').click(function () {
        layer.prompt({formType:2,maxlength: 500,title:'请填写退回原因'},function(val, index){
            show_loading();
            taskArg['memo'] = val;
            $.post(rurl('scm/impOrder/examine'),taskArg,function (res) {
                if(isSuccess(res)){
                    parent.reloadList();
                    closeThisWin('操作成功');
                }
            });
        });
    });
    //保存修改明细
    $('.save-edit-member').click(function () {
        var members = jsonList($('#orderMemberForm').serializeJson());
        postJSON('scm/impOrder/saveInspectionMemberEdit',{"orderId":id,"members":members},function (res) {
            show_success('修改成功');
            inspec.renderData();
        });
    });
    var confirmInspection = function(updateRate){
        show_loading();
        $.post(rurl('scm/impOrder/confirmInspection'),{'id':id,'updateRate':updateRate},function (res) {
            if(isSuccess(res)){
                parent.reloadList();
                closeThisWin('验货完成');
            }
        });
    }
    //验货完成
    $('.confirm-inspection').click(function(){
       if(getNowFormatDate().substring(0,7) != $('#inspection_order_date').text().substring(0,7)){
            confirm_inquiry('当前订单日期存在跨月是否需要更新海关汇率？',function () {
                confirmInspection(true);
            },function () {
                confirmInspection(false);
            });
       }else{
           confirmInspection(true);
       }
    });
    //辅助验货
    $('.auxiliary-inspection').click(function () {
        closeThisWin();
        parent.openAuxiliaryInspection(id);
    });
    //辅助验货
    $('.self-help-split').click(function () {
        layer.prompt({
            id:'splitQty',
            formType: 0,
            value: '50',
            title: '请输入每单拆单数量',
            success:function () {
                $('#splitQty').find('input').attr({'INT':''});
                initInput();
            }
        }, function(value, index, elem){
            let qty = parseInt(value);
            if(qty<1||qty>50){
                show_error('数量必须为1~50');
            }else{
                closeThisWin();
                parent.openSelfHelpSplit(id,qty);
            }
        });
    });
});
function calculationAll(e){
    var tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    if(!isEmpty(e)){
        var $that = $(e),$parent=$that.parent().parent().parent(),$quantity=$parent.find('input[name="quantity"]'),$unitPrice=$parent.find('input[name="unitPrice"]'),$totalPrice=$parent.find('input[name="totalPrice"]');
        switch ($that.attr('name')){
            case 'quantity':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
            case 'unitPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var unitPrice = Math.round(parseFloat($unitPrice.val() || '0.0')*10000)/10000;
                $totalPrice.val(Math.round(quantity*unitPrice*100)/100);
                break;
            case 'totalPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                if(quantity==0.0){$unitPrice.val('0.0000');return;}
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
        }
    }
    $.each($('#materialBody').find('tr'),function (i,o) {
        var $that = $(o);
        tquantity += Math.round(parseFloat($that.find('input[name="quantity"]').val() || '0.0')*100)/100;
        ttotalPrice += Math.round(parseFloat($that.find('input[name="totalPrice"]').val() || '0.0')*100)/100;
        tcartonNum += parseInt($that.find('input[name="cartonNum"]').val() || '0');
        tnetWeight += Math.round(parseFloat($that.find('input[name="netWeight"]').val() || '0.0')*10000)/10000;
        tgrossWeight += Math.round(parseFloat($that.find('input[name="grossWeight"]').val() || '0.0')*10000)/10000;
    });
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*100)/100);
    $grossWeightTotal.html(Math.round(tgrossWeight*100)/100);
}
function calculationSplit(e) {
    var tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    if(!isEmpty(e)){
        var $that = $(e),$parent=$that.parent().parent(),
            $quantity=$parent.find('input[name="quantity"]'),
            $unitPrice=$parent.find('input[name="unitPrice"]'),
            $totalPrice=$parent.find('input[name="totalPrice"]');
        switch ($that.attr('name')){
            case 'quantity':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
            case 'unitPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var unitPrice = Math.round(parseFloat($unitPrice.val() || '0.0')*10000)/10000;
                $totalPrice.val(Math.round(quantity*unitPrice*100)/100);
                break;
            case 'totalPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                if(quantity==0.0){$unitPrice.val('0.0000');return;}
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
        }
    }
    $.each($('#splitMemberBody').find('tr'),function (i,o) {
        var $that = $(o);
        tquantity += Math.round(parseFloat($that.find('input[name="quantity"]').val() || '0.0')*100)/100;
        ttotalPrice += Math.round(parseFloat($that.find('input[name="totalPrice"]').val() || '0.0')*100)/100;
        tcartonNum += parseInt($that.find('input[name="cartonNum"]').val() || '0');
        tnetWeight += Math.round(parseFloat($that.find('input[name="netWeight"]').val() || '0.0')*10000)/10000;
        tgrossWeight += Math.round(parseFloat($that.find('input[name="grossWeight"]').val() || '0.0')*10000)/10000;
    });
    $('#s_quantity').html(Math.round(tquantity*100)/100);
    $('#s_totalPrice').html(Math.round(ttotalPrice*100)/100);
    $('#s_cartonNum').html(tcartonNum);
    $('#s_netWeight').html(Math.round(tnetWeight*100)/100);
    $('#s_grossWeight').html(Math.round(tgrossWeight*100)/100);
}
function deleteRow(e) {
    var $per = $(e).parent().parent();
    $per.remove();
}
function autoReceivingNo($that) {
    $that.unbind().autocomplete({
        source: function (request, response){
            $.post(rurl('scm/receivingNote/selectByReceivingNoteNo'),{'customerId':customerId,'receivingNoteNo': trim(request.term)},function (res) {
                response($.map(res.data, function (item) {return {label: item.receivingNoteNo + '（' + item.totalCartonNum + '箱）', value: item.receivingNoteNo, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 500
    });
}